<template>

	<view class="content" catchtouchmove="true">
		<image class="beiY" src="../../static/beijinN.png" mode="aspectFill"></image>
		<image class="titel" @click="Toback" src="../../static/zou.png" mode="aspectFill"></image>
		<view class="titel_box">
			<view class="titel_box_one" @click="scoreClick()">
				<image class="dsfsfrf vdfgfdgf" src="../../static/one.png" mode="aspectFit"></image>
				<span class="sefregtrgfrf" :class="{ asde: columns >= 11 }">{{title}}</span>
			</view>
			<view class="titel_box_two">
				<image class="dsfsfrf" src="../../static/two.png" mode="aspectFit"></image>
				<span class="sefregtrg ">{{ setFen(fen) == "NaN" ? 0 : setFen(fen) }}分</span>
			</view>
			<view class="titel_box_three">
				<image class="dsfsfrf" src="../../static/three.png" mode="aspectFit"></image>
				<span class="sefregtrg">{{countdown}}s</span>
			</view>
		</view>
		<!-- :style="gridStyledesd" -->
		<view class="container" @touchend="endGesture">
			<canvas id="lineCanvas" style="position: absolute; top: 0; left: 0; z-index: 2; pointer-events: none;"
				canvas-id="lineCanvas" :width="canvasWidth" :height="canvasHeight" />
			<view class="grid" :style="gridStyle">
				<view v-for="(block, index) in blocks" :key="index" class="nav_box_kuai" :class="[
		       'block',
		       { 
		         active: block.active, 
		         hidden: block.hidden, 
		         'sfrgrtgthy': block.is_Selected
		       }
		     ]" 
					@click="handleClick($event, block)">
					<text v-if="block.type == 1">{{block.china}}</text>
					<image v-if="block.type == 2" class="aspectFillRRR" :src="block.jia" mode="aspectFill"></image>
				</view>
			</view>
		</view>


		<view class="fsefreghrth">
			<view class="nav_box_three_cdfrg" @click="tocustomspass(2)">
				<view class="nav_box_three_one">

				</view>
				<view class="nav_box_three_two">

				</view>
				<span class="nav_box_three_span">放弃挑战</span>
			</view>
			<view class="nav_box_three_cdfrg_crfgrt" @click="tocustomspass(1)">
				<view class="nav_box_three_one cdsgd_one">

				</view>
				<view class="nav_box_three_two cdsgd_two">

				</view>
				<span class="nav_box_three_span">重新挑战</span>
			</view>
		</view>



		<view class="nav_pass" v-if="is_regulation">

			<view class="nav_box">
				<view class="nav_box_one">
					汉字百科
				</view>
				<view class="nav_box_two">
					{{text_nav}}
				</view>

				<view class="img_koi_dsefderf" v-if="img_koi">
					<image class="imagecdfgtrhg" mode="aspectFit" :src="img_koi"></image>
				</view>
				<view class="nav_box_three" @click=" is_regulation = false ">
					<view class="nav_box_three_one" style="background-color: #00bdf1;">

					</view>
					<view class="nav_box_three_two" style="background-color: #0092ba;">

					</view>
					<span class="nav_box_three_span">知道啦</span>
				</view>
			</view>
		</view>

		<view class="nav_pass1" v-if="is_challenge">
			<view class="nav_box1">
				<view class="nav_box_one1">
					{{challenge.title}}
				</view>
				<view class="nav_box_two1">
					{{challenge.textnav}}
				</view>
				<view class="nav_box_three1" @click="toChallenge(challenge.id)">
					<view class="nav_box_three_one1">

					</view>
					<view class="nav_box_three_two1">

					</view>
					<span class="nav_box_three_span1">确定</span>
				</view>
			</view>
		</view>





		<view class="nav_pass1" v-if="is_score">
			<view class="nav_box1">
				<view class="nav_box_one1">
					本关得分
				</view>
				<view class="nav_box_two1 cdscdfvdddd">
					<image class="grgth" src="../../static/deifen.png" mode="aspectFill"></image> <text
						class="xsdcvcfccdf"> {{setFen(fen) == "NaN" ? 0 : setFen(fen)}}</text> <text class="xsdcvcf">分</text>
				</view>
				<view class="nav_box_three1" @click="scoreClick()">
					<view class="nav_box_three_one1">

					</view>
					<view class="nav_box_three_two1">

					</view>
					<span class="nav_box_three_span1">下一关</span>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		getCurrentInstance,
		ref,
		onMounted,
		watch,
		computed
	} from "vue";
	export default {



		setup() {

			let columns = ref(4)
			let widthlist = ref(300)

			const data = uni.getStorageSync('data');

			console.log(data.id, '11122')

			if (data.id >= 9) {
				columns.value = 6
				widthlist.value = 600
			} else {
				columns.value = 4
				widthlist.value = 300
			}
			const gridStyledesd = computed(() => {
				return `width: ${widthlist.value}`;
			});
			const gridStyle = computed(() => {
				return `grid-template-columns: repeat(${columns.value}, 1fr)`;
			});

			const OpenidData = uni.getStorageSync('OpenidData');




			let options_id = ref('')
			let is_challenge = ref(false)
			let challenge = ref({
				id: 1,
				title: '放弃挑战',
				textnav: '确认要放弃挑战吗？'
			})

			const toChallenge = (id) => {
				is_challenge.value = false
				if (id == 1) {
					// 重新挑战
					countdown.value = 60
					initData()
				} else {
					// 放弃挑战
					uni.navigateBack({
						delta: 1
					});
				}

			}
			const scoreClick = () => {
				uni.navigateBack({
					delta: 1
				});
				Scorerequest()
			}
			
			//成绩保存分数
			const Scorerequest = () => {
				uni.request({
					url: `https://xcx.xiaombt.com/api.php?m=llk.saveres&openid=${OpenidData.Openid.openid}&guan=${data.id}&num=${fen.value}&usetime=${countdown.value}`, // 请求的URL
					method: 'POST', // 请求方法
					header: {
						'content-type': 'application/x-www-form-urlencoded', // 请求头 如有需要自行替换
					},
					success: function(res) {


					},
					fail: function(error) {}
				})
			}




			const tocustomspass = (id) => {
				is_challenge.value = true
				console.log(id, "222222222")
				challenge.value.id = id
				if (id == 2) {
					challenge.value.title = '放弃挑战'
					challenge.value.textnav = '确认要放弃挑战吗？'
				} else if (id == 1) {
					challenge.value.title = '重新挑战'
					challenge.value.textnav = '确认要重新挑战吗？'
				}

			}

			const canvasWidth = ref(375); // 动态调整宽高
			const canvasHeight = ref(600);
			const blocks = ref([]);
			let fen = ref(0)
			let title = ref('')
			const initData = () => {
				uni.request({
					url: `https://xcx.xiaombt.com/api.php?m=llk.con&id=${data.id}`, // 请求的URL
					method: 'POST', // 请求方法
					header: {
						'content-type': 'application/x-www-form-urlencoded', // 请求头 如有需要自行替换
					},
					success: function(res) {
						fen.value = res.data.fen =='NaN'?0:res.data.fen;
						title.value = res.data.title
						countdown.value = res.data.miao
						res.data.data.forEach((item,index) => {
							item.active = false
							item.hidden = false,
							item.is_Selected = false,
							item.id = index
						});

						blocks.value = res.data.data


						resizeCanvas();
					},
					fail: function(error) {}
				})
			}

			let is_regulation = ref(false)
			let text_nav = ref('')
			let img_koi = ref('')

			let lastClickTime = ref(0);
			let lastClickIndex = ref(0);

			let list = ref([])

			const setFen = (value)=>{
				return Math.floor(100/(blocks.value.length/2) * value)
			}
			//点击事件
			const handleClick = (event, index) => {
				const currentTime = Date.now(); // 获取当前时间戳
				if (lastClickIndex.value == index.id&& currentTime - lastClickTime.value <= 300) { // 判断两次点击时间间隔小于 300ms
					clickGesture(event,index); // 执行双击事件的处理方法
				} else {
					lastClickIndex.value = index.id
					lastClickTime.value = currentTime;
					if (list.value.length == 0) {
						// 如果 list 为空，设置 index 为选中状态，并添加元素到 list
						index.is_Selected = true;
						list.value.push({
							cid: index.cid,
							type: index.type
						});
					} else {
						// 如果 list 不为空，判断当前 index 和 list 中的第一个元素的关系
						console.log(index.cid, index.type, list.value, ":??????/")

						if (index.cid == list.value[0].cid && index.type != list.value[0].type) {
							// 如果 cid 相同但 type 不同，激活并隐藏 index 和 blocks 中的元素
							index.active = true;
							index.hidden = true;

							// 在 blocks 中找到对应的元素并设置 active 和 hidden
							let one = blocks.value.find(item => item.cid == list.value[0].cid && item.type == list
								.value[0].type);
								
							if (one) {
								one.active = true;
								one.hidden = true;
								fen.value+=1;
								if(fen.value*2 >= blocks.value.length){
									console.log(fen.value,'fen.value')
									console.log('闯关成功')
									is_score.value=true;
								}
							}

							// 清空 list
							list.value = [];

						} else {
							list.value = [];
							// 如果条件不满足，重置 blocks 中的 is_Selected 为 false，清空 list
							blocks.value.forEach(item => {
								item.is_Selected = false;
							});

						}
					}



				}
				lastClickTime.value = currentTime;
			}
	

			const clickGesture = (event, index) => {
				text_nav.value = index.content
				img_koi.value = index.eximage
				is_regulation.value = true
			};


			const Toback = () => {
				uni.navigateBack()
			}

			const activeBlocks = ref([]);
			const ctx = ref(null);
			const isDragging = ref(false);

			const resizeCanvas = () => {
				const {
					windowWidth
				} = uni.getSystemInfoSync();

				canvasWidth.value = columns.value * 48;
				canvasHeight.value = Math.ceil(blocks.value.length / columns.value) * 48;




				//     const query = uni.createSelectorQuery().in(instance); // 创建查询对象，限制查询范围为当前组件




				//         // 获取 .container 元素的位置信息（包括宽高等）
				//         query.select('.container')
				//           .boundingClientRect((rect) => {

				// 			   console.log('Element Sizehahahh:', rect);
				//             // rect 包含元素的位置和尺寸信息


				// 			if(columns.value == 4){
				// 					canvasWidth.value = 200; 
				// 			}else{
				// 				canvasWidth.value = rect.width; // 保存元素的宽高信息
				// 				canvasHeight.value = (blocks.value.length / 6) * 29 ;
				// 			}
				//           })
				//           .exec(); // 执行查询



			};
			const instance = getCurrentInstance();


			const countdown = ref(20);
			let score = ref(0)
			let is_score = ref(false)
			watch(countdown, (newValue, oldValue) => {
				if (newValue === 0) {
					is_score.value = true
					let data_fen = blocks.value.filter(item => item.hidden)
					score.value = data_fen / 2
					countdown.value = data_fen / 2
				}
			});





			let timer;
			onMounted(() => {

				timer = setInterval(() => {
					if (countdown.value > 0) {
						countdown.value--;
					} else {
						clearInterval(timer);
					}
				}, 1000);

				initData()

				ctx.value = uni.createCanvasContext("lineCanvas");
			});





			const drawLines = () => {
				ctx.value && ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value);

				if (!ctx.value || activeBlocks.value.length < 2) {
					ctx.value && ctx.value.draw();
					return;
				}

				ctx.value.beginPath();
				ctx.value.setLineWidth(5);
				ctx.value.setLineCap('round')
				ctx.value.setLineJoin('round');
				ctx.value.setStrokeStyle("#fec600");



				activeBlocks.value.forEach((index, idx) => {


					console.log(index, "::;;")

					const col = index % columns.value;
					const row = Math.floor(index / columns.value);

					console.log(col, row, "::;;")

					const x = (canvasWidth.value / columns.value) * (col + 1) - (24 - (col + 1 * 2));
					const y = (canvasHeight.value / (Math.ceil(blocks.value.length / columns.value))) * (row +
						1) - (24 - (col + 1 * 2))


					console.log(x, y, "坐标")

					if (idx === 0) {
						ctx.value.moveTo(x, y);
					} else {
						ctx.value.lineTo(x, y);
					}
				});

				ctx.value.stroke();
				ctx.value.draw();




			};



			const activateBlock = (index) => {
				if (
					index === null ||
					blocks.value[index].hidden ||
					activeBlocks.value.includes(index)
				)
					return;
				blocks.value[index].active = true;
				activeBlocks.value.push(index);
				drawLines();
			};

			const containerRect = ref(null);
			//手指按下
			const startGesture = (event, index) => {
				console.log(event, index, ":::2544444")
				isDragging.value = true;
				activateBlock(index);
				const query = uni.createSelectorQuery().in(instance);

				query
					.select(".container")
					.boundingClientRect((rect) => {

						containerRect.value = rect;
					})
					.exec();

			};

			
			//手指按下后移动触发
			const moveGesture = (event) => {

				if (!isDragging.value || !containerRect.value) return;
				console.log(event,'-----');
				const touch = event.touches[0];
				const x = touch.clientX - containerRect.value.left;
				const y = touch.clientY - containerRect.value.top;

				const col = Math.floor((x / canvasWidth.value) * columns.value);
				const row = Math.floor((y / canvasHeight.value) * columns.value);

				const index = row * columns.value + col;
				console.log(index ,":22222")
				 // < blocks.value.length
				if (index >= 0) {
					activateBlock(columns.value==4 && index>=4?index-4:index);
				}
			};



			const endGesture = () => {
				if (isDragging.value && activeBlocks.value.length >= 2) {
					const [firstIndex, secondIndex] = activeBlocks.value;
					const arr = Object.values(activeBlocks.value);

					const firstBlock = blocks.value[firstIndex];
					const secondBlock = blocks.value[arr[arr.length - 1]];

					if (firstBlock.cid === secondBlock.cid) {
						firstBlock.hidden = true;
						secondBlock.hidden = true;
					}

					activeBlocks.value.forEach((index) => {
						blocks.value[index].active = false;
					});

					activeBlocks.value.length = 0;
					isDragging.value = false;

					drawLines();
				} else {
					activeBlocks.value.forEach((index) => {
						blocks.value[index].active = false;
					});
					activeBlocks.value.length = 0;
					isDragging.value = false;
					drawLines();
				}

				const allHidden = blocks.value.every(item => item.hidden);
				if (allHidden) {
					is_score.value = true
					score.value = blocks.value.length / 2
					clearInterval(timer);
				}


			};
			return {
				canvasWidth,
				canvasHeight,
				blocks,
				startGesture,
				moveGesture,
				endGesture,
				clickGesture,
				is_regulation,
				text_nav,
				Toback,
				countdown,
				challenge,
				is_challenge,
				tocustomspass,
				toChallenge,
				score,
				is_score,
				scoreClick,
				Scorerequest,
				fen,
				title,
				img_koi,
				columns,
				gridStyle,
				handleClick,
				setFen
			};
		},
	};
</script>



<style scoped>
	page {
		overflow: hidden;
	}

	image {
		width: 0;
		height: 0;
	}

	.content {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		z-index: -1;
	}

	.beiY {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.titel {
		position: fixed;
		top: 125rpx;
		left: 32rpx;
		width: 48rpx;
		height: 48rpx;

	}

	.nav {
		position: fixed;
		top: 50%;
		left: 50%;
		width: 408rpx;
		transform: translate(-50%, -50%);
		display: flex;

		flex-wrap: wrap;
		justify-content: space-between;

	}

	.nav::after {
		content: '';
		width: 160rpx;
		border: 1rpx solid transparent
	}

	.item {
		width: 96rpx;
		height: 96rpx;
		background-image: url('../../static/baise.png');
		background-size: 100%;
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.imgsge {
		width: 40%;
		height: 40%;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.chengong {
		position: absolute;
		left: 50%;
		top: 35rpx;
		width: 44rpx;
		height: 44rpx;
		margin-left: -22rpx;
	}

	.contentlevel {
		position: absolute;
		left: 50%;
		top: 80rpx;
		width: 80rpx;
		height: 44rpx;
		color: #fff;
		font-size: 24rpx;
		margin-left: -32rpx;
	}

	.nav_pass {
		position: fixed;
		top: 50%;
		left: 50%;
		width: 650rpx;
		padding: 30rpx;
		box-sizing: border-box;
		border: 3px solid rgb(254, 198, 0);
		background: rgb(247, 255, 235);
		transform: translate(-50%, -50%);

	}

	.nav_box {
		width: 100%;
		height: 100%;
		border: 1rpx solid rgb(254, 198, 0);
	}

	.nav_box_one {
		width: 100%;
		height: 96rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-weight: bold;
		font-size: 40rpx;
		color: #fff;
		border-radius: 0px 0px 50px 50px;
		background: rgb(254, 198, 0);
	}

	.nav_box_two {
		font-size: 32rpx;
		margin: 68rpx 56rpx;
		line-height: 52rpx;
	}

	.nav_box_three {
		position: relative;
		width: 288rpx;
		margin: 0 auto;
		height: 106rpx;
		margin-bottom: 46rpx;
	}

	.nav_box_three_one {
		position: absolute;
		top: 0;
		width: 100%;
		z-index: 555;
		height: 96rpx;
		border-radius: 40px;
		background: rgb(254, 53, 0);
	}

	.nav_box_three_two {
		position: absolute;
		bottom: 0;
		width: 100%;
		height: 96rpx;
		border-radius: 40px;
		background: rgb(199, 41, 0);
	}

	.nav_box_three_span {
		position: absolute;
		top: 50%;
		left: 50%;
		z-index: 666;
		font-weight: bold;
		font-size: 36rpx;
		color: #fff;
		transform: translate(-50%, -58%);
	}


	.titel_box {
		position: fixed;
		top: 250rpx;
		left: 0;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.titel_box_one {
		width: 216rpx;
		height: 80rpx;
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.titel_box_two {
		width: 216rpx;
		height: 90rpx;
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.titel_box_three {
		width: 216rpx;
		height: 90rpx;
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dsfsfrf {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.vdfgfdgf {
		width: 90%;
		height: 80%;
	}

	.sefregtrgfrf {
		position: absolute;
		/* margin-top: -10rpx; */
		margin-left: 33rpx;
		font-weight: bold;
		font-size: 25rpx;
		color: #fff;
	}

	.sefregtrg {
		position: absolute;
		margin-top: -10rpx;
		margin-left: 30rpx;
		font-weight: bold;
		color: #fff;
	}

	.nav_box_three_cdfrg {
		position: fixed;
		left: 66rpx;
		/* bottom: 200rpx; */
		width: 288rpx;
		height: 106rpx;
	}

	.nav_box_three_cdfrg_crfgrt {
		position: fixed;
		right: 66rpx;
		width: 288rpx;
		height: 106rpx;
	}

	.fsefreghrth {
		position: fixed;
		bottom: 200rpx;
		width: 600rpx;
		height: 106rpx;
		display: flex;
		justify-content: space-around;
	}

	.cdsgd_one {
		background: rgb(254, 198, 0);
	}

	.cdsgd_two {
		background: rgb(201, 157, 0);
	}

	.csdcdfvcsdvf {
		margin-bottom: 10rpx;
		margin-left: 5rpx;
	}

	.container {
		position: absolute;
		top: 50%;
		left: 50%;
		/* width: 600rpx; */
		transform: translate(-50%, -50%);
	}

	.grid {
		display: grid;
		/* grid-template-columns: repeat(var(--columns), 1fr); */
		/* grid-gap: 20rpx; */
		position: relative;

		z-index: 10;
		justify-items: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}

	.aspectFillRRR {
		width: 50%;
		height: 50%;
	}

	.nav_box_kuai {
		width: 96rpx !important;
		height: 96rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.block {
		width: 100%;
		aspect-ratio: 1;
		/* background-color: #3498db; */
		background-image: url('../../static/baise.png');
		background-size: 100%;
		border-radius: 5px;
		transition: background-color 0.3s;
	}

	.block.active {
		/* background-color: #e74c3c; */
	}

	.block.hidden {
		/* visibility: hidden; */
	}

	canvas {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1;
	}

	.block {
		transition: transform 0.3s ease, opacity 0.3s ease;
	}

	.block.hidden {
		/* transform: scale(0); */
		opacity: 0;
	}

	.nav_pass1 {
		position: fixed;
		top: 50%;
		left: 50%;
		width: 650rpx;
		padding: 30rpx;
		box-sizing: border-box;
		border: 3px solid rgb(254, 198, 0);
		background: rgb(247, 255, 235);
		transform: translate(-50%, -50%);

	}

	.nav_box1 {
		width: 100%;
		height: 100%;
		border: 1rpx solid rgb(254, 198, 0);
	}

	.nav_box_one1 {
		width: 100%;
		height: 96rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-weight: bold;
		font-size: 40rpx;
		color: #fff;
		border-radius: 0px 0px 50px 50px;
		background: rgb(254, 198, 0);
	}

	.nav_box_two1 {
		font-size: 32rpx;
		margin: 68rpx 56rpx;
		line-height: 52rpx;
		text-align: center;
	}

	.nav_box_three1 {
		position: relative;
		width: 288rpx;
		margin: 0 auto;
		height: 106rpx;
		margin-bottom: 46rpx;
	}

	.nav_box_three_one1 {
		position: absolute;
		top: 0;
		width: 100%;
		z-index: 555;
		height: 96rpx;
		border-radius: 40px;
		background: rgb(0, 189, 241);
	}

	.nav_box_three_two1 {
		position: absolute;
		bottom: 0;
		width: 100%;
		height: 96rpx;
		border-radius: 40px;

		background: rgb(0, 146, 186);
	}

	.nav_box_three_span1 {
		position: absolute;
		top: 50%;
		left: 50%;
		z-index: 666;
		font-weight: bold;
		font-size: 40rpx;
		color: #fff;
		transform: translate(-50%, -58%);
	}

	.grgth {
		width: 112rpx;
		height: 112rpx;
	}

	.cdscdfvdddd {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.xsdcvcfccdf {
		margin-left: 20rpx;
		font-size: 100rpx;
		color: #fe3500;
	}

	.xsdcvcf {
		margin-top: 30rpx;
		margin-left: 20rpx;
		color: #ffc700;
	}

	.img_koi_dsefderf {
		width: 100%;
		height: 200rpx;
		margin-bottom: 50rpx;

	}

	.imagecdfgtrhg {
		width: 100%;
		height: 100%;
	}

	.is_Selected {
		background-color: #fe3500 !important;
	}

	.sfrgrtgthy {
		/* background-image: url('../../static/dddd.png') !important; */
		position: relative;
	
	}
	.sfrgrtgthy::after{
		content: '';
		width: 80%;
		height: 80%;
		position: absolute;
		left: 50%;
		top: 47%;
		transform: translate(-50%,-50%);
		z-index: 10;
		background-color: rgba(0,0,0,.4) !important;
	}

	.asde {
		margin-top: 0px !important;
	}
</style>